#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import os
import sys
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker

# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from config.config import settings
from src.utils.data_generator import data_generator

def get_required_fields_from_db(object_name):
    """从数据库获取指定对象的必填字段，排除系统字段"""
    try:
        # 创建数据库连接
        engine = create_engine(settings.database_url)
        SessionLocal = sessionmaker(bind=engine)
        session = SessionLocal()
        
        # 查询必填字段
        query = text("""
            SELECT field_api_name, field_type, field_label_zh, field_label_en
            FROM field_schema 
            WHERE object_api_name = :object_name AND is_required = 1
        """)
        
        result = session.execute(query, {"object_name": object_name})
        required_fields = []
        system_fields = ['_id', '_createdAt', '_updatedAt']
        for row in result:
            if row.field_api_name in system_fields:
                continue
            required_fields.append({
                "field_api_name": row.field_api_name,
                "field_type": row.field_type,
                "field_label_zh": row.field_label_zh,
                "field_label_en": row.field_label_en
            })
        
        session.close()
        return required_fields
        
    except Exception as e:
        print(f"数据库查询失败: {str(e)}")
        return []

def add_required_field_frameworks():
    """为 test_frameworks.json 添加缺少必填字段的测试用例框架"""
    frameworks_file = "data/test_frameworks.json"
    
    if not os.path.exists(frameworks_file):
        return False
    
    # 读取现有数据
    with open(frameworks_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 为每个对象添加必填字段测试用例框架
    for object_name, object_data in data.items():
        frameworks = object_data.get("frameworks", [])
        
        # 获取该对象的必填字段
        required_fields = get_required_fields_from_db(object_name)
        
        for required_field in required_fields:
            field_name = required_field["field_api_name"]
            field_label = required_field["field_label_zh"] or required_field["field_label_en"] or field_name
            
            # 创建缺少必填字段的测试用例框架
            missing_required_framework = {
                "case_name": f"创建记录-缺少必填字段-{field_label}",
                "case_type": "create",
                "scenario": "exception",
                "description": f"测试缺少必填字段{field_label}({field_name})的情况",
                "test_data_type": "invalid",
                "target_field": field_name,
                "expected_result": f"创建失败，{field_label}字段必填"
            }
            
            frameworks.append(missing_required_framework)
    
    # 保存更新后的数据
    with open(frameworks_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    return True

def add_required_field_cases():
    """为必填字段添加缺少必填字段的测试用例"""
    test_cases_file = "data/test_cases.json"
    
    if not os.path.exists(test_cases_file):
        return False
    
    # 读取现有数据
    with open(test_cases_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 为每个对象添加必填字段测试用例
    for object_name, object_data in data.items():
        test_cases = object_data.get("test_cases", [])
        
        # 获取该对象的必填字段
        required_fields = get_required_fields_from_db(object_name)
        
        for required_field in required_fields:
            field_name = required_field["field_api_name"]
            field_label = required_field["field_label_zh"] or required_field["field_label_en"] or field_name
            
            # 生成所有字段的正常数据
            all_fields = [
                {"field_api_name": "phone_73c280f2783", "field_type": "mobileNumber"},
                {"field_api_name": "decimal_a446e77c109", "field_type": "decimal"},
                {"field_api_name": "number_a33398bfae5", "field_type": "number"},
                {"field_api_name": "datetime_bfae52d8694", "field_type": "datetime"},
                {"field_api_name": "richText_76d22d35024", "field_type": "richText"},
                {"field_api_name": "multilingual_24673c280f2", "field_type": "multilingual"},
                {"field_api_name": "date_398bfae52d8", "field_type": "date"},
                {"field_api_name": "option_e52d86948bb", "field_type": "option"},
                {"field_api_name": "text_7ea7d6a3339", "field_type": "text"},
                {"field_api_name": "bigint_7d6a33398bf", "field_type": "bigint"},
                {"field_api_name": "boolean_e206a267520", "field_type": "boolean"},
                {"field_api_name": "email_f2783b49d9a", "field_type": "email"},
            ]
            
            # 生成完整的正常数据
            complete_data = data_generator.generate_test_data(all_fields, True)
            
            # 去掉必填字段，构造缺少必填字段的数据
            missing_required_data = complete_data.copy()
            if field_name in missing_required_data:
                del missing_required_data[field_name]
            
            # 创建缺少必填字段的测试用例
            missing_required_case = {
                "case_name": f"创建记录-缺少必填字段-{field_label}",
                "case_type": "create",
                "scenario": "exception",
                "description": f"测试缺少必填字段{field_label}({field_name})的情况",
                "test_data": missing_required_data,
                "expected_result": f"创建失败，{field_label}字段必填"
            }
            
            test_cases.append(missing_required_case)
    
    # 保存更新后的数据
    with open(test_cases_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    return True

def main():
    """主函数"""
    # 添加必填字段测试用例框架
    add_required_field_frameworks()
    
    # 添加必填字段测试用例
    add_required_field_cases()

if __name__ == "__main__":
    main() 